<template>
  <el-dialog
    class="collect-money-dialog"
    width="900px"
    :visible.sync="dialogVisible"
    title="业务收款"
    :close-on-click-modal="false"
    :append-to-body="true"
    v-dialogDrag="true"
    @open="handleDialogOpen"
    @closed="handleDialogClosed"
  >
    <el-form ref="collectMoneyForm" :model="formData" :rules="formRules" size="small" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="合同编号:" prop="agreementNumber">
            <el-input
              v-model="formData.agreementNumber"
              placeholder="请输入"
              clearable
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户:" prop="organizationName">
            <el-input
              v-model="formData.organizationName"
              placeholder="请输入"
              clearable
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="应收金额:" prop="actualAmount">
            <el-input
              v-model="formData.actualAmount"
              placeholder="请输入"
              clearable
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="应收余额:" prop="unPaymentAmount">
            <el-input
              v-model="formData.unPaymentAmount"
              placeholder="请输入"
              clearable
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="" prop="" label-width="25px">
            <div style="margin-bottom: 10px;">
              <label style="margin-right: 20px;">产品/服务:</label>
            </div>
            <el-table
              style="width: 100%"
              :data="productList"
            >
              <el-table-column type="index" label="序号" align="center" width="50">
              </el-table-column>
              <el-table-column label="产品" prop="productId" align="center" min-width="200">
                <template slot="header">
                  <span style="color: red;">*</span>
                  <span>产品/服务</span>
                </template>
                <template slot-scope="scope">
                  <div style="display: flex;">
                    <el-select
                      style="flex: 1;"
                      v-model="scope.row.productId"
                      :clearable="true"
                      :filterable="true"
                      :disabled="true"
                    >
                      <el-option
                        v-for="(item, index) in productList"
                        :key="index"
                        :label="item.productName"
                        :value="item.productId"
                      >
                        <span>{{ item.productCode }}：{{ item.productName }}</span>
                      </el-option>
                    </el-select>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="数量" align="center" prop="quantity" min-width="80">
                <template slot="header">
                  <span style="color: red;">*</span>
                  <span>数量</span>
                </template>
                <template slot-scope="scope">
                  <el-input-number
                    style="width: 100%;"
                    v-model="scope.row.quantity"
                    placeholder="请输入"
                    :min="0"
                    :precision="0"
                    :controls="false"
                    :disabled="true"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="销售单价" align="center" prop="salesUnitPrice" min-width="80">
                <template slot="header">
                  <span style="color: red;">*</span>
                  <span>销售单价</span>
                </template>
                <template slot-scope="scope">
                  <el-input-number
                    style="width: 100%;"
                    v-model="scope.row.salesUnitPrice"
                    placeholder="请输入"
                    :min="0"
                    :precision="2"
                    :controls="false"
                    :disabled="true"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="金额" align="center" prop="amount" min-width="80">
                <template slot="header">
                  <span style="color: red;">*</span>
                  <span>金额</span>
                </template>
                <template slot-scope="scope">
                  <el-input-number
                    style="width: 100%;"
                    v-model="scope.row.amount"
                    placeholder="请输入"
                    :min="0"
                    :precision="2"
                    :controls="false"
                    :disabled="true"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="备注" align="center" prop="remark" min-width="120">
                <template slot-scope="scope">
                  <el-input
                    style="width: 100%;"
                    v-model="scope.row.remark"
                    placeholder="请输入"
                    :disabled="true"
                  ></el-input>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="收款单位:" prop="paymentInfoId">
            <div style="display: flex;">
              <el-select
                v-if="!isAddPayment"
                style="width: 100%;"
                v-model="formData.paymentInfoId"
                clearable
                filterable
                @change="(value) => {
                  const findRes = paymentList.find(item => item.paymentInfoId == value)
                  formData.paymentInfoId = findRes ? findRes.paymentInfoId : ''
                  formData.unitName = findRes ? findRes.unitName : ''
                }"
              >
                <el-option
                  v-for="(item, index) in paymentList"
                  :key="index"
                  :label="item.unitName"
                  :value="item.paymentInfoId"
                ></el-option>
              </el-select>
              <el-input v-else style="width: 100%;" v-model="formData.unitName" placeholder="请输入收款单位名称"></el-input>
              <el-button style="margin-left: 4px;" icon="el-icon-plus" size="mini" plain type="primary" @click="handleAddInvoicHead">{{ !isAddPayment ? '新增收款账户' : '选择收款账户'}}</el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="业务员:" prop="businessUserName">
            <el-input
              style="width: 100%;"
              v-model="formData.businessUserName"
              placeholder="请输入"
              :disabled="true"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="收款金额:" prop="agreementPaymentAmount">
            <el-input-number
              style="width: 100%;"
              v-model="formData.agreementPaymentAmount"
              placeholder="请输入"
              :min="0"
              :precision="2"
              :controls="false"
              :disabled="!!recordRow"
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="收款人:" prop="paymentUser">
            <el-select
              style="width: 100%;"
              v-model="formData.paymentUser"
              clearable
              filterable
            >
              <el-option
                v-for="(item, index) in userList"
                :key="index"
                :label="item.nickName"
                :value="item.userId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="收款时间:" prop="paymentTime">
            <el-date-picker
              style="width: 100%;"
              popper-class="payment-time-date-picker"
              ref="paymentTimeDatePicker"
              v-model="formData.paymentTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择"
              @focus="handlePaymentTimeFocus"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="备注:" prop="remark">
            <el-input
              type="textarea"
              rows="3"
              maxlength="100"
              show-word-limit
              v-model="formData.remark"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- <el-row>
        <el-col :span="24">
          <el-form-item label="附件:" prop="agreementFileOssId">
            <el-upload
              ref="attachmentUploadRef"
              :action="uploadParams.url"
              :headers="uploadParams.headers"
              :before-upload="handleBeforeUpload"
              :on-success="handleSuccessFile"
              :on-error="handleErrorFile"
              :on-remove="handleRemoveFile"
              :on-preview="handlePreviewFile"
              :file-list="attachmentFileList"
              multiple
            >
              <el-button icon="el-icon-upload" size="mini" plain type="primary">添加附件</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row> -->
    </el-form>

    <div class="dialog-footer" slot="footer">
      <el-button style="margin-right: 50px;" type="primary" @click="handleSave">提交</el-button>
      <el-button @click="dialogVisible = false">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { userListingIgnorePermission } from '@/api/system/user'
import { collectMoneyOper, collectMoneyRecordEdit } from '@/api/person/collectmoney'
import { getPaymentListAll } from '@/api/person/payment'
import { contractDetail } from '@/api/person/contract'
import { getToken } from '@/utils/auth'

export default {
  name: 'CollectMoneyDialog',
  components: {},
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    row: {
      type: Object,
      default: () => ({})
    },
    recordRow: {
      type: Object,
      default: null
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.show
      },
      set(value) {
        this.$emit('update:show', value)
      }
    }
  },
  data() {
    return {
      userList: [],
      paymentList: [],
      isAddPayment: false,
      formData: {},
      formRules: {
        agreementId: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        agreementPaymentAmount: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        paymentTime: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        paymentUser: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        remark: []
      },
      // 文件上传参数
      uploadParams: {
        url: process.env.VUE_APP_BASE_API + '/system/oss/upload',
        headers: {
          Authorization: 'Bearer ' + getToken(),
          'Content-Disposition': 'inline',
        },
      },
      attachmentFileList: [],
      productList: [],
    }
  },
  created() {
    this.initFormData()
  },
  methods: {
    // 弹框打开时
    handleDialogOpen() {
      this.formData.agreementId = this.row.agreementId || ''
      this.formData.agreementNumber = this.row.agreementNumber || ''
      this.formData.organizationName = this.row.organizationName || ''
      this.formData.actualAmount = this.row.actualAmount || ''
      this.formData.unPaymentAmount = this.row.unPaymentAmount || ''
      this.formData.paymentUser = this.$store.state.user.userInfo?.userId || ''
      this.formData.agreementPaymentAmount = this.row.agreementPaymentAmount || this.row.unPaymentAmount || '';
      this.formData.businessUserName = this.row.businessUserName || ''
      // this.attachmentFileList = JSON.parse(this.row.agreementFileOssId || '[]')

      if (this.recordRow) {
        Object.assign(this.formData, this.recordRow)
      }

      if (this.userList.length <= 0) {
        userListingIgnorePermission().then(res => {
          this.userList = res.data || []
        }).catch(err => {})
      }

      getPaymentListAll().then(res => {
        this.paymentList = res.data || []
      }).catch(err => {})

      contractDetail(this.row.agreementId).then(res => {
        this.productList = res.data.products || []
      }).catch(err => {})
    },
    // 弹框关闭时
    handleDialogClosed() {
      this.initFormData()
      this.$refs.collectMoneyForm.resetFields()
      this.attachmentFileList = []
    },
    // 初始化表单数据
    initFormData() {
      this.formData = {
        agreementId: '',
        agreementNumber: '',
        organizationName: '',
        actualAmount: '',
        unPaymentAmount: '',
        paymentInfoId: '',
        unitName: '',
        businessUserName: '',
        agreementPaymentAmount: undefined,
        paymentTime: '',
        paymentUser: '',
        remark: '',
      }
      this.isAddPayment = false
    },
    // 获取表单数据
    getFormData() {
      const data = JSON.parse(JSON.stringify(this.formData))
      // data.agreementFileOssId = JSON.stringify(this.attachmentFileList.map(item => ({
      //   ossId: item.response?.data.ossId || item.ossId,
      //   url: item.response?.data.url || item.url,
      //   name: item.response?.data.name || item.name
      // })))
      return data
    },
    // 点击保存
    handleSave() {
      this.$refs.collectMoneyForm.validate(valid => {
        if (!valid) return
        let fn = collectMoneyOper
        if (this.recordRow) fn = collectMoneyRecordEdit
        const data = this.getFormData()
        fn(data).then(res => {
          this.$message.success('操作成功')
          this.dialogVisible = false
          this.$emit('refresh')
        }).catch(err => {})
      })
    },
    // 新增抬头编号
    handleAddInvoicHead() {
      this.isAddPayment = !this.isAddPayment
      this.formData.paymentInfoId = ''
      this.formData.unitName = ''
    },
    // 文件上传前
		handleBeforeUpload(file) {
			// let isPDF = (file.type === 'application/pdf')
			// if (!isPDF) {
			// 	this.$message.warning('仅支持pdf格式，请重新上传!')
			// }
			// return isPDF
      return true
		},
    // 文件上传成功
    handleSuccessFile(res, file, fileList) {
			if (res.code == 500) {
				return this.$message.error(res.msg)
			}
			this.attachmentFileList = fileList
    },
    // 文件上传失败
    handleErrorFile(err, file, fileList) {
      this.$message.error('文件上传失败')
    },
    // 移除文件
    handleRemoveFile(file, fileList) {
      this.attachmentFileList = fileList
		},
    // 预览文件
    handlePreviewFile(file, fileList) {
			if (file.response && file.response.data) {
				window.open(file.response.data.url, 'PDF', '')
			} else if (file.url) {
				window.open(file.url, 'PDF', '')
			}
		},
    handlePaymentTimeFocus() {
      this.$nextTick(() => {
        const table = document.querySelector('.payment-time-date-picker')?.querySelector('.el-date-table')
        if (!table) return
        const paymentTimeDatePickerRef = this.$refs['paymentTimeDatePicker']
        table.addEventListener('dblclick', () => {
          paymentTimeDatePickerRef.pickerVisible = false
        })
      })
    }
  },
}
</script>

<style lang="scss" scoped>
.collect-money-dialog {

  ::v-deep .el-dialog__body {
    max-height: 90vh;
    overflow-y: auto;
  }

  .append {
    position: absolute;
    right: 10px;
  }

  .el-divider {
    margin-top: 5px;
  }
}
</style>
